﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace HSIA
{
    public partial class FrmReceiverEdit : Form
    {
        DatabaseObject dbo;
        public string sID = "";
        public string sName = "";
        public string sReceiverKeyId = "";
        public string sIPCOM = "";
        public int iType = 0;
        int iEditType = 0;
        DataRow drReceiver;
        DataTable dtAccount, dtDeviceType;

        public FrmReceiverEdit(DatabaseObject vdbo, int piEditType, DataRow pdr, DataTable dtDeviceType)
        {
            dbo = vdbo;
            iEditType = piEditType;
            drReceiver = pdr;
            this.dtDeviceType = dtDeviceType;
            InitializeComponent();
        }

        private void FrmPlaceEdit_Load(object sender, EventArgs e)
        {
            dtAccount = dbo.GetDataTableBySql("Select * From Sys_Account", "Account");
            cbCompany_Code.DataSource = dtAccount;
            cbCompany_Code.DisplayMember = "Company_Name";
            cbCompany_Code.ValueMember = "Company_Code";

            cbDeviceType.DataSource = dtDeviceType; //BuildVersion();
            cbDeviceType.DisplayMember = "Version_Name";
            cbDeviceType.ValueMember = "Version_Type";

            foreach (DataRow dr in dbo.dtMeasureType.Rows)
            {
                int iTag = 0;
                if (int.TryParse(dr["Tag"].ToString(), out iTag) && iTag > 0)
                {
                    cbTag.Items.Add(dr["Name"].ToString());
                }
            }

            if (iEditType == 0)
            {
                Text = dbo.GetLanguage(5) + Text;//"新增"
                SetMeasureTag(cbTag, "1"); //cbTag.SelectedValue = 1;
                tbSendCycle.Text = tbRFCycle.Text = "60";
                tbTimeZone.Text = "0";
                cbDeviceType.SelectedIndex = 1;
                //cbVersion.Text = "AMATE";
            }
            else
            {
                Text = dbo.GetLanguage(90) + Text;//"修改" 
                tbKeyId.Enabled = false;
                if (drReceiver != null)
                {
                    try
                    {
                        SetMeasureTag(cbTag, drReceiver["Tag"].ToString()); //cbTag.SelectedValue = 1;
                        cbCompany_Code.SelectedValue = drReceiver["Company_Code"];
                        cbDeviceType.SelectedValue = drReceiver["DeviceType"];
                    }
                    catch (Exception)
                    {

                    }
                }
            }

            InitParam(true);
            cbTag.SelectedValueChanged += cbTag_SelectedIndexChanged;
            CreateMeasureType(drReceiver, GetMeasureTag(cbTag));

            this.Text = dbo.GetLanguage(237);
            btOK.Text = dbo.GetLanguage(193); //193确定
            btnCancel.Text = dbo.GetLanguage(51);//51取消
        }

        private void CreateMeasureType(DataRow drReceiver, string sTag)
        {
            TCM.Controls.Clear();
            //string sTag = Convert.ToString(iRTag, 2).PadRight(8, '0');
            //int iIndex = -1;
            foreach (DataRow dr in dbo.dtMeasureType.Rows)
            {
                int iMTag = 0;
                if (int.TryParse(dr["Tag"].ToString(), out iMTag) && iMTag <= 0) continue;

                int iIndex = Convert.ToInt32(dr["FieldIndex"]) - 1;

                int iWarnType = 0;
                if (int.TryParse("9", out iWarnType) && iWarnType == 0 || sTag[iIndex].ToString() == "0") continue;

                int iX = 7, iY = 0;
                string sID = dr["ID"].ToString();
                TabPage tpMeasure = new TabPage(dr["Name"].ToString());
                tpMeasure.Name = "tp" + sID;
                tpMeasure.Tag = sID;

                TextBox tb; Label lbl;

                string sWarnType = Convert.ToString(iWarnType, 2).PadLeft(4, '0');
                if (sWarnType[0].ToString() == "1")
                {
                    lbl = new Label();
                    lbl.Tag = lbl.Name = "lblU" + sID;
                    lbl.Text = dbo.GetLanguage(337) + ":";
                    lbl.Location = new Point(iX, iY * 30 + 10);

                    tb = new TextBox();
                    tb.Name = "tbU" + sID;
                    tb.Tag = lbl.Text;
                    tb.Size = new Size(72, 23);
                    tb.Location = new Point(iX * 12, iY * 30 + 10);
                    if (drReceiver != null)
                    {
                        if (drReceiver.Table.Columns.Contains("U" + sID))
                            tb.Text = drReceiver["U" + sID].ToString();
                        else tb.Enabled = false;
                    }

                    tpMeasure.Controls.Add(tb);
                    tpMeasure.Controls.Add(lbl);
                }
                iY++;
                if (sWarnType[3].ToString() == "1")
                {
                    lbl = new Label();
                    lbl.Tag = lbl.Name = "lblL" + sID;
                    lbl.Text = dbo.GetLanguage(169) + ":";
                    lbl.Location = new Point(iX, iY * 30 + 10);

                    tb = new TextBox();
                    tb.Name = "tbL" + sID;
                    tb.Tag = lbl.Text;
                    tb.Size = new Size(72, 23);
                    tb.Location = new Point(iX * 12, iY * 30 + 10);
                    if (drReceiver != null)
                    {
                        if (drReceiver.Table.Columns.Contains("L" + sID))
                            tb.Text = drReceiver["L" + sID].ToString();
                        else tb.Enabled = false;
                    }

                    tpMeasure.Controls.Add(tb);
                    tpMeasure.Controls.Add(lbl);
                }

                TCM.Controls.Add(tpMeasure);
            }
            //gbValueArea.Size = new Size(199, iH * 25);
        }

        private string GetMeasureTag(CheckComboBox cbTag)
        {
            string sMeasureType = "";
            int[] iMeasureType = new int[dbo.dtMeasureType.Select("Tag>" + 0).Length];
            for (int i = 0; i < iMeasureType.Length; i++)
            {
                if (cbTag.CheckBoxItems[i + 1].CheckState == CheckState.Checked)
                {
                    iMeasureType[i] = 1;
                }
            }
            //DataRow[] drs = cbTag.Properties.GetCheckedItems() as DataRow[];
            //foreach (DataRow dr in drs)
            //{
            //    iMeasureType[int.Parse(dr["Tag"].ToString())] = 1;
            //}
            for (int i = iMeasureType.Length - 1; i >= 0; i--)
            {
                sMeasureType += iMeasureType[i].ToString();
            }
            //foreach (int i in iMeasureType)
            //{
            //    sMeasureType += i.ToString();
            //}
            return sMeasureType.PadLeft(8, '0');
        }

        private void SetMeasureTag(CheckComboBox cbTag, string sTag)
        {
            sTag = sTag.PadLeft(8, '0');
            DataRow[] drM = dbo.dtMeasureType.Select("Tag>" + 0);
            foreach (DataRow dr in drM)
            {
                int FieldIndex = Convert.ToInt32(dr["FieldIndex"]) - 1;
                if (sTag[FieldIndex] == '1')
                {
                    cbTag.CheckBoxItems[FieldIndex - 6].CheckState = CheckState.Checked;
                }
            }
        }

        private DataTable BuildVersion()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Version_Name", Type.GetType("System.String"));
            dt.Columns.Add("Version_Code", Type.GetType("System.String"));

            dt.Rows.Add(new object[] { "老版", "AT-II" });
            dt.Rows.Add(new object[] { "新版", "AT-600" });

            return dt;
        }

        /// <summary>
        /// 加载参数
        /// </summary>
        public void InitParam(bool bLbl)
        {
            foreach (Control control in this.Controls)
            {
                if (control is Label && bLbl)
                {
                    Label lbl = control as Label;
                    if (lbl.Tag != null) lbl.Text = dbo.GetLanguage(lbl.Tag);
                    continue;
                }
                if (drReceiver != null)
                {
                    if (control is TextBox)
                    {
                        string sColumnID = control.Name.TrimStart('t', 'b');
                        if (drReceiver.Table.Columns.Contains(sColumnID))
                            control.Text = drReceiver[sColumnID].ToString();
                        else control.Enabled = false;
                    }
                    else if (control is TabControl && !bLbl)
                    {
                        foreach (TabPage tp in TCM.TabPages)
                        {
                            foreach (Control c in tp.Controls)
                            {
                                if (c is TextBox)
                                {
                                    string sColumnID = c.Name.TrimStart('t', 'b');
                                    if (drReceiver.Table.Columns.Contains(sColumnID))
                                        c.Text = drReceiver[sColumnID].ToString();
                                    else c.Enabled = false;
                                }
                            }
                        }
                    }
                }
            }
        }


        private bool CheckData()
        {
            bool b = true;
            int iValue = 0;
            foreach (Control c in this.Controls)
            {
                if (c.Enabled && c.Tag != null && c.Text.Trim() == "")
                {
                    MessageBox.Show(string.Format(dbo.GetLanguage(1), c.Tag.ToString()), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Warning);//" 区域信息不能为空,请选择或输入!");
                    c.Focus();
                    return false;
                }
                if (c is TextBox && c.Enabled)
                {
                    if (int.TryParse(c.Text.Trim(), out iValue))
                    {
                        if (c.Name == "tbKeyId")
                            c.Text = iValue.ToString().PadLeft(10, '0');
                        else c.Text = iValue.ToString();
                    }
                    else if (c.Name == "tbSensorIds")
                    {
                        if (c.Text.Split(',').Length == 0) return false;
                    }
                    else if (c.Name == "tbPhone")
                    {

                    }
                    else return false;
                }

            }

            double d, dU = 0, dL = 0;
            foreach (TabPage tp in TCM.TabPages)
            {
                foreach (Control c in tp.Controls)
                {
                    if (c.Name.StartsWith("tb") && c.Enabled)
                    {
                        if (double.TryParse(c.Text, out d))
                        {
                            if (c.Name == "tbU" + tp.Tag) dU = d;
                            else if (c.Name == "tbL" + tp.Tag) dL = d;
                        }
                        else
                        {
                            TCM.SelectedTab = tp;
                            MessageBox.Show(c.Tag + dbo.GetLanguage(465) + dbo.GetLanguage(464), dbo.GetLanguage(103), MessageBoxButtons.OK, MessageBoxIcon.Error);//"字符格式错误,请重新输入!");
                            c.Focus();
                            return false;
                        }
                    }
                }
                int iMax = (tp.Tag.ToString() == "T") ? 126 : 100;
                int iMin = (tp.Tag.ToString() == "T") ? -51 : -1;
                string sMsg = "";
                if (!PublicFunc.JudgeValue(new double[] { dU, dL }, iMax, iMin))
                {
                    sMsg = dbo.GetLanguage(369) + "(" + iMin + "-" + iMax + ")";//"超出范围,请重新输入!", "提示"
                    b = false;
                }
                if (b && dU != iMax && dL != iMin && dU < dL)
                {
                    sMsg = dbo.GetLanguage(469) + dbo.GetLanguage(303) + dbo.GetLanguage(470) + dbo.GetLanguage(472) + dbo.GetLanguage(466) + dbo.GetLanguage(468) + dbo.GetLanguage(303) + dbo.GetLanguage(470) + dbo.GetLanguage(472);
                    //低温报警值应小于高温报警值!", "提示"
                    b = false;
                }
                if (!b)
                {
                    TCM.SelectedTab = tp;
                    MessageBox.Show(sMsg, dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return b;
                }
            }

            return b;
        }

        private string AddRec()
        {
            string sInsertSQL = "";//" + sWarnFieldValue + 
            string sKey = "", sValue = "";
            foreach (Control c in this.Controls)
            {
                if (c.Name.StartsWith("tb") && c.Enabled)
                {
                    sKey += c.Name.TrimStart('t', 'b') + ",";
                    sValue += "'" + c.Text + "',";
                }
                else if (c.Name == "cbTag")
                {
                    sKey += "Tag,";
                    sValue += "'" + GetMeasureTag(cbTag) + "',";
                }
                else if (c.Name.StartsWith("cb") && c.Enabled)
                {
                    ComboBox cb = c as ComboBox;
                    sKey += cb.Name.TrimStart('c', 'b') + ",";
                    sValue += "'" + cb.SelectedValue + "',";
                }
            }
            if (sKey != "" && sValue != "")//& sKey.Split(',').Length == sValue.Split(',').Length
            {
                sKey += "ConnectType,";
                sValue += "'0',";

                sKey += "CreateDate,";
                sValue += "'" + DateTime.Now.ToString() + "',";

                sInsertSQL += string.Format("insert into Sys_Receiver({0}) values({1})", sKey.TrimEnd(','), sValue.TrimEnd(','));
            }

            sKey = sValue = "";
            foreach (TabPage tp in TCM.TabPages)
            {
                foreach (Control c in tp.Controls)
                {
                    if (c.Name.StartsWith("tb") && !c.Enabled)
                    {
                        sKey += c.Name.TrimStart('t', 'b') + ",";
                        sValue += "'" + c.Text + "',";
                    }
                }
            }
            if (sKey != "" && sValue != "")//& sKey.Split(',').Length == sValue.Split(',').Length
            {
                sKey += "KeyId,";
                sValue += "'" + sReceiverKeyId + "',";
                sInsertSQL += string.Format("insert into Sys_Receiver_Threshold({0}) values({1})", sKey.TrimEnd(','), sValue.TrimEnd(','));
            }
            return sInsertSQL;
        }

        private string EditRec()
        {
            string sInsertSQL = "";
            string sValue = "";
            foreach (Control c in this.Controls)
            {
                if (c.Name.StartsWith("tb") && c.Enabled)
                {
                    string sColumnID = c.Name.TrimStart('t', 'b');
                    if (drReceiver[sColumnID].ToString() != c.Text)
                    {
                        drReceiver[sColumnID] = c.Text;
                        sValue += sColumnID + "='" + c.Text + "',";
                    }
                }
                else if (c.Name == "cbTag")
                {
                    string sTag = GetMeasureTag(cbTag);
                    if (drReceiver["Tag"].ToString() != sTag)
                    {
                        drReceiver["Tag"] = sTag;
                        sValue += cbTag.Name.TrimStart('c', 'b') + "='" + sTag + "',";
                    }
                }
                else if (c.Name.StartsWith("cb") && c.Enabled)
                {
                    ComboBox cb = c as ComboBox;
                    string sColumnID = cb.Name.TrimStart('c', 'b');
                    if (cb.SelectedValue != null && drReceiver[sColumnID].ToString() != cb.SelectedValue.ToString())
                    {
                        drReceiver[sColumnID] = cb.SelectedValue.ToString();
                        sValue += sColumnID + "='" + cb.SelectedValue + "',";
                    }
                }

            }
            if (sValue != "")
            {
                sInsertSQL += string.Format("update Sys_Receiver set {1} where KeyId='{0}';", sReceiverKeyId, sValue.TrimEnd(','));
            }

            sValue = "";
            foreach (TabPage tp in TCM.TabPages)
            {
                foreach (Control c in tp.Controls)
                {
                    if (c.Name.StartsWith("tb") && c.Enabled)
                    {
                        string sColumnID = c.Name.TrimStart('t', 'b');
                        if (drReceiver[sColumnID].ToString() != c.Text)
                        {
                            drReceiver[sColumnID] = c.Text;
                            sValue += sColumnID + "='" + c.Text + "',";
                        }
                    }
                }
            }
            if (sValue != "")
                sInsertSQL += string.Format("update Sys_Receiver_Threshold set {1} where KeyId='{0}';", sReceiverKeyId, sValue.TrimEnd(','));

            return sInsertSQL;
        }


        private void btOK_Click(object sender, EventArgs e)
        {
            if (CheckData())
            {
                sReceiverKeyId = tbKeyId.Text.Trim();
                string sMode, sInsertSQL;
                if (iEditType == 0)
                {
                    sMode = dbo.GetLanguage(5);
                    sInsertSQL = AddRec();
                }
                else
                {
                    sMode = dbo.GetLanguage(90);// "编辑";
                    sInsertSQL = EditRec();
                }
                string sRet = dbo.ExcuteSQL(sInsertSQL);
                bool b = false;
                if (sRet == "OK")
                {
                    sRet = sMode + string.Format(dbo.GetLanguage(239), tbKeyId.Text);// "接收器成功!";
                    if (drReceiver != null) drReceiver.Table.AcceptChanges();
                    b = true;
                    AmateBussiness.SendMasgeToServer(dbo, PC.WM_DeviceRefresh, 0);
                }
                else
                {
                    if (drReceiver != null) drReceiver.Table.RejectChanges();
                }
                MessageBox.Show(sRet, dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (b) this.DialogResult = DialogResult.OK;
            }
        }

        private void FrmPlaceEdit_Shown(object sender, EventArgs e)
        {
            //tbReceiverId.Focus();

            //this.FormBorderStyle = FormBorderStyle.FixedSingle;
            //this.StartPosition = FormStartPosition.CenterScreen;
            //this.ShowInTaskbar = false;
            //this.MaximizeBox = false;
            //this.MinimizeBox = false;
            //if (iType == 0) txtIPCOM.Text = sIPCOM;
        }

        private void FrmPlaceEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Control) && (e.KeyCode == Keys.Enter)) btOK_Click(null, null);
        }

        private void txtReceiverId_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 13)
            {
                e.Handled = true;
            }
        }

        private void txtReceiverId_TextChanged(object sender, EventArgs e)
        {
            //int i;
            //if (!Int32.TryParse(txtReceiverId.Text, out i))
            //{
            //    SendKeys.Send("^z");
            //    return;
            //}

            ////if (txtName.Text.Trim() == txtReceiverId.Text) 
            //if(txtName.Text.Trim()=="") txtName.Text = txtReceiverId.Text;
            //if ((iEditType == 0)&&(iType == 0)) txtIPCOM.Text = sIPCOM + txtReceiverId.Text;
        }

        private void cbTag_SelectedIndexChanged(object sender, EventArgs e)
        {
            CreateMeasureType(drReceiver, GetMeasureTag(cbTag));
        }

        private void btAddCompany_Click(object sender, EventArgs e)
        {
            FrmAccountEdit fa = new FrmAccountEdit(dbo, dtAccount);
            if (fa.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                dtAccount.AcceptChanges();
                cbCompany_Code.DataSource = dtAccount;
            }
        }
    }
}
